package m

import (
	"GameServer/Common/utils"

	"github.com/globalsign/mgo/bson"

	log "github.com/sirupsen/logrus"

	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"
)

var (
	BSGameTableName string = "BSGame"
)

// Boss老虎机
type BSGame struct {
	BaseM
	Uid                 bson.ObjectId   `bson:"_id" json:"_id"`
	Round               int64           `bson:"round" json:"round"` // 回合数
	Monster             *CardMonster    `bson:"monster" json:"monster"`
	CardBuffs           []*CardBuff     `bson:"cardBuffs" json:"cardBuffs"`                     // 卡牌buff
	AttBrustPercent     int64           `bson:"attBrustPercent" json:"attBrustPercent"`         // 玩家打怪，增伤百分比
	DmgAccu             int64           `bson:"dmgAccu" json:"dmgAccu"`                         // 玩家打怪，累计伤害
	DmgAccuBonusGain    map[int64]int64 `bson:"dmgAccuBonusGain" json:"dmgAccuBonusGain"`       // 已领取累伤奖励ID
	BossDefeatBonusGain map[int64]int64 `bson:"bossDefeatBonusGain" json:"bossDefeatBonusGain"` // 已领取BOSS击退奖励ID
	EndTime             int64           `bson:"endTime" json:"endTime"`                         // 本次战斗结束时间
	Status              int64           `bson:"status" json:"status"`                           // 状态 0 正常  1 胜利  2 失败 3 主动退出 4 已经领取奖励
	PlayerShield        int64           `bson:"playerShield" json:"playerShield"`               // 玩家护盾值
	ActivId             int64           `bson:"activId" json:"activId"`                         // 活动ID
	LastActivId         int64           `bson:"lastActivId" json:"lastActivId"`                 // 上次活动ID

	MaxHP int64 `bson:"maxHP" json:"maxHP"` // 血量上限值
	HP    int64 `bson:"hp" json:"hp"`       // 当前血量值

	MaxEnergy int64 `bson:"maxEnergy" json:"maxEnergy"` // 最大能量值
	Energy    int64 `bson:"energy" json:"energy"`       // 当前能量值

	DmgBonus int64 `bson:"dmgBonus" json:"dmgBonus"` // 当前伤害加成
	DmgIncre int64 `bson:"dmgIncre" json:"dmgIncre"` // 叠满能量，增加的伤害

	Wager int64 `bson:"wager" json:"wager"` // 下注金币值
	Spin  int64 `bson:"spin" json:"spin"`   // 老虎机倍率

	ShopBuyCnt int64 `bson:"shopBuyCnt" json:"shopBuyCnt"` // 商店购买 记录已买次数
	ShopState  int64 `bson:"shopState" json:"shopState"`   // 商店开启状态 0.未开启 1.商店开启，或已开启
}

func NewBSGame() cache.EntryI {
	return &BSGame{
		CardBuffs:           make([]*CardBuff, 0),
		Status:              -1,
		DmgAccuBonusGain:    make(map[int64]int64, 0),
		BossDefeatBonusGain: make(map[int64]int64, 0),
	}
}

// 保存信息
func (this *BSGame) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert(BSGameTableName, bson.M{"_id": this.Uid}, this)
	if err != nil {
		return
	}
	return
}

func (this *BSGame) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		this.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		this.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "BSGame_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return this.LoadData()
}

// 加载数据
func (this *BSGame) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne(BSGameTableName, bson.M{"_id": this.Uid}, nil, &this)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if this.DmgAccuBonusGain == nil {
		this.DmgAccuBonusGain = make(map[int64]int64, 0)
	}
	if this.BossDefeatBonusGain == nil {
		this.BossDefeatBonusGain = make(map[int64]int64, 0)
	}
	return
}

// 更新数据
func (this *BSGame) Update(val *BSGame) {
	Cache.Put(BSGameTableName, this.Uid.Hex(), val)
	val.UpdateData()
}

// 删除数据
func (this *BSGame) Delete() (err error) {
	Cache.Remove(BSGameTableName, this.Uid.Hex())
	return dbmodule.MgoDB.GameDB.Remove(BSGameTableName, bson.M{"_id": this.Uid})
}

// 获取多人战斗数据M，不会检测EndTime有效性
func (u *User) GetBSGame() (r *BSGame) {
	v, _ := Cache.Get(BSGameTableName, u.Uid.Hex())
	r = v.(*BSGame)
	return
}

// 获取多人战斗数据M，进行活动ID，与EndTime检测
func (u *User) GetBSGameByActId(actId int64, combatEndTime int64) (r *BSGame) {
	v, _ := Cache.Get(BSGameTableName, u.Uid.Hex())
	r = v.(*BSGame)
	nowTime := utils.TNow().Unix()
	if r != nil {
		if r.ActivId != actId || (r.EndTime+86400) < nowTime {
			r.Uid = u.Uid
			r.LastActivId = r.ActivId
			r.ActivId = actId
			r.Round = 1
			//Monster为空，会在8101进入战斗时候重置怪物信息
			r.CardBuffs = make([]*CardBuff, 0)
			r.DmgAccu = 0
			r.DmgAccuBonusGain = make(map[int64]int64, 0)
			r.BossDefeatBonusGain = make(map[int64]int64, 0)
			r.Status = 0
			r.PlayerShield = 0
			r.EndTime = combatEndTime
			r.Update(r)
		}
	}
	return
}

// 是否已经获得，累计伤害奖励，传入奖励ID
func (this *BSGame) IsGainBonus_DmgAccu(bonusId int64) (isGain bool) {
	_, isGain = this.DmgAccuBonusGain[bonusId]
	return
}

// 是否已经获得，BOSS击退奖励，传入BOSS的Tid
func (this *BSGame) IsGainBonus_BossDefeat(bossTid int64) (isGain bool) {
	_, isGain = this.BossDefeatBonusGain[bossTid]
	return
}

// 设置该ID的，累伤奖励，为已经获取状态
func (this *BSGame) SetGainBonus_DmgAccu(bonusId int64) {
	if this.DmgAccuBonusGain == nil {
		this.DmgAccuBonusGain = make(map[int64]int64, 0)
	}
	this.DmgAccuBonusGain[bonusId] = 1
	this.Update(this)
}

// 设置该ID的，BOSS击退奖励，为已经获取状态
func (this *BSGame) SetGainBonus_BossDefeat(bossTid int64) {
	if this.BossDefeatBonusGain == nil {
		this.BossDefeatBonusGain = make(map[int64]int64)
	}
	this.BossDefeatBonusGain[bossTid] = 1
	this.Update(this)
}

func (this *BSGame) UpdateDmgAccu(newDmgAccu int64) {
	this.DmgAccu = newDmgAccu
	this.Update(this)
}
